<template>
  <div class="box">
    <div class="card-container">
      <el-row :gutter="10">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
          <el-col :span="19" :offset="0">
            <!-- <el-form-item label="厂商代码" prop="facCode">
            <el-input v-model="queryParams.facCode" placeholder="请输入厂商代码" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item> -->

            <!-- <el-form-item label="厂商简称" prop="facShortName">
            <el-input v-model="queryParams.facShortName" placeholder="请输入厂商简称" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item> -->

            <el-form-item label="设备型号" prop="model">
              <el-input v-model="queryParams.model" placeholder="请输入设备型号" clearable size="small"
                @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="软件版本" prop="version">
              <el-input v-model="queryParams.version" placeholder="请输入版本" clearable size="small"
                @keyup.enter.native="handleQuery" />
            </el-form-item>

            <!-- <el-form-item label="是否启用" prop="isEnable">
              <el-select v-model="queryParams.isEnable" placeholder="请选择是否启用" clearable
                size="small">
                <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                  :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item> -->
          </el-col>

          <el-col :span="5" :offset="0">
            <el-form-item>
              <el-button icon="el-icon-search" size="mini" @click="handleQuery">搜索
              </el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button   icon="el-icon-plus" size="mini" v-hasPermi="['version:add']"
          @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button   icon="el-icon-delete" size="mini" :disabled="multiple"
          v-hasPermi="['version:remove']" v-show="!multiple" @click="handleDelete">删除</el-button>
      </el-col>
    </el-row> -->
    <div class="card-container">
      <div class="body-title">
        <div class="body-title-left">
          软件版本管理
          <!-- <div class="header-button">
            <div @click="queryButton(true)" :class="queryBut ? 'true' : ''">
              正常
            </div>
            <div @click="queryButton(false)" :class="!queryBut ? 'true' : ''">
              停用
            </div>
          </div> -->
        </div>
        <div class="body-title-right">
          <el-button icon="el-icon-plus" size="mini" v-hasPermi="['version:add']" @click="handleAdd">新增</el-button>
          <el-button icon="el-icon-delete" size="mini" :disabled="multiple" v-hasPermi="['version:remove']"
            v-show="!multiple" @click="handleDelete">删除</el-button>
          <!-- <el-button  size="mini" :disabled="single" v-show="!multiple" @click="handleUpdate">
            修改</el-button> -->
          <!-- <el-button  size="mini" :disabled="multiple" v-hasPermi="['version:remove']" v-show="!multiple"
            @click="handleDelete">删除</el-button> -->
          <!-- <el-button  size="mini" v-show="!multiple" @click="handleExport">导出</el-button> -->
          <!-- <el-button   icon="el-icon-plus" size="mini" v-hasPermi="['version:add']"
            @click="handleAdd">新增
          </el-button> -->
        </div>
      </div>
      <el-table v-loading="loading" height="500" ref="table" :data="versionList" :row-key="getRowKeys"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="checkSelectable" width="55" :reserve-selection="true"
          align="center" />
        <el-table-column label="设备型号" align="center" prop="modelIds" show-overflow-tooltip min-width="150"
          :formatter="formatModel" />
        <el-table-column label="设备类型" align="center" prop="deviceType" :formatter="formatType" />
        <!-- <el-table-column label="设备厂商" align="center" prop="facturer" /> -->
        <el-table-column label="软件版本" align="center" prop="version" />
        <el-table-column label="版本说明" align="center" prop="desc">
          <template slot-scope="scope">
            <span>{{ scope.row.desc || "暂无" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="center" prop="createTime" min-width="130">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="70" label="推送次数" align="center" prop="upgradeCount" />
        <el-table-column min-width="70" label="是否启用" align="center" prop="isEnable">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.isEnable" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="120" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" v-hasPermi="['version:edit']" @click="handleUpdate(scope.row)">
              编辑</el-button>
            <!-- <el-button size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)" >删除
            </el-button> -->
            <el-button size="mini" type="text" :disabled="scope.row.isEnable == '1'"
              v-hasPermi="['versionPushTotalLog:add']" @click="handlePush(scope.row)">
              推送</el-button>
            <el-button size="mini" type="text" v-hasPermi="['dataPushTotalLog:query']"
              @click="handleUpdateLog(scope.row)">
              记录</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改设备版本对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="500px" append-to-body>
      <div class="card-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备型号" prop="modelIds">
          <el-select v-model="form.modelIds" multiple :disabled="isEdit" :style="'width:340px;'" placeholder="请选择设备型号">
            <el-option v-for="item in options" :key="item.modelId" :label="item.model" :value="item.modelId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="软件版本" prop="version">
          <el-input v-model="form.version" maxlength="20" placeholder="请输入软件版本" />
        </el-form-item>
        <el-form-item label="版本说明" prop="desc">
          <el-input v-model="form.desc" type="textarea" maxlength="100" placeholder="请输入版本说明" />
        </el-form-item>
        <el-form-item label="上传类型" prop="type">
          <el-select v-model="form.type" :disabled="title == '编辑'" :style="'width:340px;'" placeholder="请选择上传类型">
            <el-option label="上传文件" value="1">
            </el-option>
            <el-option label="上传地址" value="2">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- :show-file-list="false" -->
        <el-form-item v-if="form.type == '1'" label="文件上传" required true prop="">
          <el-upload :action="upload.url" ref="upload" v-if="title !== '编辑'" :auto-upload="false" :limit="10"
            :on-change="handeFile" :before-remove="fileRemove" :file-list="upload.fileList">
            <el-button size="small" icon="el-icon-upload2" :disabled="isupload">点击上传</el-button>
          </el-upload>
          <div v-else>
            {{ form.softwareSourceName }}
            <el-button style="margin-left: 20px" @click="handledown" type="text">下载</el-button>
          </div>
        </el-form-item>
        <el-form-item v-else-if="form.type == '2'" label="下载地址" required true prop="">
          <el-input v-model="form.versionDowmloadUrl" type="text" @blur="handleLoadurl" :disabled="isurl"
            placeholder="请输入下载地址" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnable">
          <el-radio-group v-model="form.isEnable">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
     
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoad" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 升级记录 -->
    <el-dialog :title="'推送记录'" :close-on-click-modal="false" v-if="updateLogOpen" :visible.sync="updateLogOpen"
      width="1200px" append-to-body>
      <update-log :row="updateList" @handleCheck="handleCheck" />
    </el-dialog>

    <!-- 升级失败设备列表 -->
    <el-dialog :title="failTitle" :close-on-click-modal="false" v-if="updateFailOpen" :visible.sync="updateFailOpen"
      width="1200px" append-to-body>
      <update-fail :row="updateFailList" />
    </el-dialog>

    <!-- 推送升级 -->
    <el-dialog :title="'推送升级'" :close-on-click-modal="false" v-if="updatePushOpen" :visible.sync="updatePushOpen"
      width="800px" append-to-body>
      <update-push :row="updatePushList" @push="handlePushSchedule" @cancel="updatePushOpen = false" />
    </el-dialog>

    <!-- 推送升级进度 -->
    <el-dialog :title="'推送升级进度'" :close-on-click-modal="false" v-if="pushScheduleOpen" :visible.sync="pushScheduleOpen"
      width="800px" append-to-body>
      <push-schedule @close="pushScheduleOpen = false" :row="pushScheduleList" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listVersion,
  getVersion,
  delVersion,
  addVersion,
  updateVersion,
  getDeviceMode,
  down,
} from "@/api/version/version";
import updateLog from "./updateLog.vue";
import updateFail from "./updateFail.vue";
import updatePush from "./updatePush.vue";
import pushSchedule from "./pushSchedule.vue";
export default {
  name: "Version",
  dicts: ["sys_file_type", "sys_update_mode", "sys_normal_disable"],
  components: { updateLog, updateFail, updatePush, pushSchedule },
  data() {
    return {
      isurl: false,
      isupload: false,
      queryBut: true,
      failTitle: "推送失败设备列表",
      upload: {
        url: "",
        fileList: [],
        file: null,
      },
      buttonLoad: false,
      pushScheduleOpen: false,
      pushScheduleList: {},
      updatePushOpen: false,
      updatePushList: {},
      updateFailOpen: false,
      updateFailList: {},
      updateList: {},
      updateLogOpen: false,
      facList: [],
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      // showSearch: true,
      // 总条数
      total: 0,
      // 设备版本表格数据
      versionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        version: null,
        facCode: null,
        facShortName: null,
        model: null,
        isEnable: 0,
      },
      isEdit: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        modelIds: [
          { required: true, message: "请选择设备型号", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择上传类型", trigger: "change" },
        ],
        version: [
          {
            required: true,
            message: "软件版本不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getMode();
  },
  activated() {
    this.getList();
  },
  methods: {
    formatType(val) {
      switch (val.deviceType) {
        case '1':
          return '预警终端';
        case '2':
          return '预警喇叭';
        case '1,2':
          return '预警终端、预警喇叭';
        default:
          break;
      }
    },
    formatModel(row) {
      let modelList = [];
      this.options.filter((item) => {
        row.modelIds.includes(item.modelId) && modelList.push(item.model);
      });
      return modelList.join();
    },
    fileRemove(file, fileList) {
      // this.form[`softwareSourceNames`].push(file.name);
      // this.form[`softwareHdfsNames`].push(res.data.filename);
      const index = this.form[`softwareSourceNames`].indexOf(file.name);
      this.form[`softwareSourceNames`].splice(index, 1);
      this.form[`softwareHdfsNames`].splice(index, 1);
      this.upload.fileList = fileList;
      this.isurl = false
    },
    checkSelectable(row) {
      // console.log(row.upgradeCount <= 0,"row")
      // return row.upgradeCount <= 0;
      return true
    },
    async handledown() {
      this.download(
        "/file/download",
        {
          filename: this.form.softwareHdfsName,
        },
        `${this.form.softwareSourceName}`
      );
    },
    queryButton(type) {
      this.queryBut = type;
      if (this.queryBut) {
        this.queryParams.isEnable = "0";
      } else {
        this.queryParams.isEnable = "1";
      }
      this.handleQuery();
    },
    getRowKeys(row) {
      return row.versionId;
    },
    handeFile(file, fileList) {
      // this.upload.file = file;
      console.log(123)
      if (1024 * 1024 <= file.size / 1024) {
        this.$modal.msgError("上传文件大小不能超过1G");
        return false;
      } else {
        console.log(fileList, 'fileList')
        this.upload.fileList = fileList;
        this.uploadFun(file.raw);
      }
    },
    handlePushSchedule(row, toData) {
      // this.pushScheduleList = {
      //   row,
      //   toData,
      // };
      this.updateFailList = row;
      this.failTitle = "推送设备列表";
      this.updateFailOpen = true
      // this.pushScheduleOpen = true;
    },
    handlePush(row) {
      this.updatePushList = row;
      this.updatePushOpen = true;
    },
    handleUpdateLog(row) {
      this.updateList = row;
      this.updateLogOpen = true;
    },
    handleCheck(row, sta) {
      this.updateFailList = row;
      if (sta == "0") {
        this.updateFailList.upgradeStatus = sta;
        this.failTitle = "推送失败设备列表";
      } else {
        this.updateFailList.upgradeStatus = "";
        this.failTitle = "推送设备列表";
      }

      this.updateFailOpen = true;
    },
    async getMode() {
      let res = await getDeviceMode();
      if (res.code === 200) {
        this.options = res.data;
      }
    },
    handleLoadurl() {
      if (this.form.versionDowmloadUrl) {
        this.isupload = true
      } else {
        this.isupload = false
      }
    },
    /** 查询设备版本列表 */
    getList() {
      this.loading = true;
      listVersion(this.queryParams).then((response) => {
        this.versionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        modelIds: [],
        version: null,
        versionDesc: null,
        softwareSourceNames: [],
        softwareHdfsNames: [],
        isEnable: "0",
      };
      this.upload = {
        url: "",
        fileList: [],
        file: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$forceUpdate();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.versionId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      this.isurl = false
      this.isupload = false
      // this.getMode();
      this.facList = await this.$api.getFact();
      this.buttonLoad = false;
      this.open = true;
      this.isEdit = false;
      this.title = "新增";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const versionId = row.versionId || this.ids;
      this.isEdit = row.upgradeCount > 0;
      getVersion(versionId).then((response) => {
        this.form = response.data;
        // this.getMode();
        if (response.data.versionDowmloadUrl) {
          this.form.type = '2'
        } else {
          this.form.type = '1'
        }
        this.buttonLoad = false;
        this.open = true;
        this.title = "编辑";
      });
    },
    async uploadFun(file, name) {
      const formData = new FormData();
      formData.append("file", file);
      this.submitLoad = true;
      this.buttonLoad = true;
      try {
        const res = await this.$api.handelUpload(formData);
        if (res.code == 200) {
          this.buttonLoad = false;
          this.submitLoad = false;
          this.isurl = true
          this.form[`softwareSourceNames`].push(file.name);
          this.form[`softwareHdfsNames`].push(res.data.filename);
        }
      } catch (error) {
        // this.$refs.upload.abort(file)
        this.$refs.upload.uploadFiles = this.$refs.upload.uploadFiles.filter(
          (item) => {
            return item.uid !== file.uid;
          }
        );
        this.buttonLoad = false;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (this.form.versionId != null) {
            updateVersion(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.upload.fileList.length > 0 || this.form.versionDowmloadUrl) {
              // const res = await addVersion(this.form);
              // if (res.code == 200) {
              //     this.$modal.msgSuccess('新增成功');
              //     this.open = false;
              //     this.getList();
              // }
              this.buttonLoad = true;
              addVersion(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.buttonLoad = false;
                this.open = false;
                this.getList();
              });
            } else {
              this.$modal.msg("必须上传至少一个文件或输入下载地址");
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const versionIds = row.versionId || this.ids;
      this.$modal
        .confirm('是否确认删除设备版本编号为"' + versionIds + '"的数据项？')
        .then(function () {
          return delVersion(versionIds);
        })
        .then(() => {
          this.$refs.table.clearSelection();
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "version/version/export",
        {
          ...this.queryParams,
        },
        `version_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100%;
  padding: 20px;
}


.body-title {
  display: flex;
  position: relative;
  // justify-content: space-between;
  align-items: center;
}

.body-title-left {
  display: flex;
  height: 100%;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 600;
  color: #fff;
  line-height: 64px;
}

.body-title-right {
  position: absolute;
  right: 0;
}

.header-button {
  display: flex;
  align-items: center;
  margin-left: 30px;

  >div {
    width: 80px;
    height: 28px;
    text-align: center;
    margin-bottom: 0px;
    line-height: 28px;
    cursor: pointer;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    font-size: 14px;
    font-weight: 400;
  }

  >div:nth-child(1) {
    border-right-width: 0px;
    border-top-left-radius: 3px;
    border-bottom-left-radius: 3px;
  }

  >div:nth-child(2) {
    border-left-width: 0px;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
  }

  .true {
    border: 1px solid #409eff !important;
    color: #409eff;
  }
}
</style>
